#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: con00_base.py 
@version:
@time: 2022/01/13 
"""
# generate table
from TapException.CONNECTOR import *
from TapClientConnector.connector.tap_connector_decorator import *
from TapClientCore.T01_init_conf.v2_init.others import build_table

from db_info import *


class TAPConnectorBase:
    DB_INFO = None
    FORMAT_DB_INFO = None
    TABLE_DESCRIPTION = None

    CURRENT_TABLE = None

    connector = None
    connector_type = None
    connector_database = None
    connector_schema = None

    def __init__(self, kwargs: dict):
        self.connector_type = kwargs.get('database_type')
        self.connector_schema = kwargs.get('database_owner')
        self.connector_database = kwargs.get('database_name')
        self.DB_INFO = kwargs
        self.FORMAT_DB_INFO = self._db_info_format(kwargs)
        self.CURRENT_TABLE = self.salt

    @staticmethod
    def _db_info_format(kwargs) -> dict:
        format_info = None
        if kwargs.get('database_type').lower() == 'kafka':
            format_info = {"kafkaPatternTopics": kwargs["kafkaPatternTopics"],
                           "kafkaBootstrapServers": kwargs["kafkaBootstrapServers"],
                           "user": kwargs["database_username"],
                           "password": kwargs["plain_password"],
                           "new": kwargs.get('new')
                           }
        elif kwargs.get('database_type').lower() in ['activemq', 'rabbitmq', 'rocketmq']:
            return kwargs
        else:
            if kwargs.get('database_type').lower() in ['hive', 'hbase']:
                format_info = {
                    'host': kwargs.get('database_host'),
                    'port': int(kwargs.get('python_port')),
                    'user': kwargs.get('database_username'),
                    'password': kwargs.get('plain_password'),
                    'database': kwargs.get('database_name'),
                }
            elif kwargs.get('database_type').lower() in ['redis']:
                format_info = {
                    'host': kwargs.get('database_host'),
                    'port': int(kwargs.get('database_port')),
                    'user': kwargs.get('database_username'),
                    'password': kwargs.get('plain_password'),
                    'database': kwargs.get('database_name'),
                    'data_struct': kwargs.get('data_struct')
                }
            else:
                format_info = {
                    'host': kwargs.get('database_host'),
                    'port': int(kwargs.get('database_port')),
                    'user': kwargs.get('database_username'),
                    'password': kwargs.get('plain_password'),
                    'database': kwargs.get('database_name'),
                }

        return format_info

    # **** Connector ****

    @connector_exec_logger
    def _exec(self, sql):
        with self.connector.cursor() as cursor:
            cursor.execute(sql)
            self.connector.commit()

    def _query(self, sql) -> list:
        with self.connector.cursor() as cursor:
            cursor.execute(sql)
            self.TABLE_DESCRIPTION = [one[0] for one in cursor.description]
            query_result = list(cursor.fetchall())
            return query_result

    def query_get_column(self, sql) -> list:
        with self.connector.cursor() as cursor:
            cursor.execute(sql)
            self.TABLE_DESCRIPTION = cursor.description
            tmp = []
            for one in self.TABLE_DESCRIPTION:
                tmp.append(one[0])
            return tmp

    # **** util ****

    @staticmethod
    def execMany(func, sql: list) -> list:
        result = []
        for _ in sql:
            result.append(func(_))
        if result:
            return result

    @property
    def salt(self):
        import random
        import time
        if build_table.get(self.connector_type) is None:
            return f"{build_table.get(self.connector_type.lower())}{time.time_ns() + random.randint(1, 100)}"
        return f"{build_table.get(self.connector_type)}{time.time_ns() + random.randint(1, 100)}"

    @staticmethod
    async def append_table(query_result, table_list):
        for i in query_result:
            table_list.append(i[0])
        return table_list
        # logger.info('去除dbo_开头, _CT结尾的cdc表')
        # for i in query_result:
        #     if i[0].startswith('dbo_') and i[0].endswith('_CT'):
        #         pass
        #     else:
        #         table_list.append(i[0])
        # return table_list

    # **** CURD ****

    def exec(self, sql):
        if sql is None:
            logger.warning('exec string is None')
            return
        return self._exec(sql)

    @connector_query_logger
    def query(self, sql) -> list:
        return self._query(sql)

    def count(self, query_data):
        return len(self.query(query_data))

    # # **** show db, table ****
    #
    def show_dbs(self):
        raise NotSupport

    def show_tables(self):
        raise NotSupport

    # **** close ****

    def close(self):
        self.connector.close()

    def __del__(self):
        try:
            self.close()
        except Exception as e:
            logger.info(e)
            logger.info('connector has closed')

    # ***** Generate *****

    # **DDL**

    def generate_create(self, table_column, table):
        raise NotSupport

    def generate_drop(self, table):
        raise NotSupport

    # **DML**

    def generate_insert(self, insert, table):
        raise NotSupport

    def generate_update(self, update, where, table):
        raise NotSupport

    def generate_delete(self, where, table):
        raise NotSupport

    def generate_select(self, column, where, table):
        raise NotSupport
